""" -*- coding: utf-8 -*-"""
from functools import wraps
from flask import g, request, jsonify
from models import User  # 改为绝对导入

def authenticate():
    """用户认证中间件"""
    # 跳过无需认证的端点
    if request.path in ['/users/login', '/users/register']:
        return

    token = request.headers.get('Authorization')
    if not token or not token.startswith('Bearer '):
        return jsonify({'error': 'Missing or invalid token'}), 401

    try:
        user_id = token.replace('Bearer ', '')
        user = User.query.get(user_id)
        if not user:
            return jsonify({'error': 'User not found'}), 401

        g.current_user = user
    except Exception as e:
        return jsonify({'error': f'Authentication failed: {str(e)}'}), 401

def has_role(required_role):
    """检查用户是否具有指定角色"""
    user = getattr(g, 'current_user', None)
    if not user:
        return False
    return user.role == required_role

def require_role(required_role):
    """装饰器：要求用户具有指定角色"""
    def decorator(func):
        @wraps(func)  # 使用 wraps 保留原始函数信息
        def wrapper(*args, **kwargs):
            if not hasattr(g, 'current_user'):
                return jsonify({'error': 'Authentication required'}), 401
            if not has_role(required_role):
                return jsonify({'error': f'Required role: {required_role}'}), 403
            return func(*args, **kwargs)
        return wrapper
    return decorator